package com.tbit.uqbike.tergateway.wa205pkg;

import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.ATerPkg;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.WA205DeEnCoder;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.tergateway.pojo.TerBattery;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by MyWin on 2018/5/22 0022.
 */
public class Heart extends ATerPkg {
    private static Logger logger = LoggerFactory.getLogger(ControlInfo.class);
    public int time;
    public String sn;
    public String lon;
    public String lat;
    public String safeStatus;
    public String batvol;

    @Override
    public void doBusiness() {
        TerTempData terTempData = TerGatewayData.getTerTempDataByMno(this.mno);
        Date dt = new Date(this.time);
        // 更新最后状态
        terTempData.updateStatus(dt, Integer.parseInt(this.safeStatus), this.getSignalStatus());
        // 获取电量对象
        TerBattery terBattery = getTerBattery();
        // 处理电量
        TerGatewayMain.terEvnet.terRecvNewBattery(terTempData, terBattery);
        // 检查离线指令
        if (terTempData.getOfflineOrderFlag()) {
            terTempData.checkOfflineOrder();
        }
    }

    private int getSignalStatus() {
        int i = 0;
        return i;
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo info, AProtocol protocol) {
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
        WA205DeEnCoder.getCommRsp(byteBuf, "1");
        return byteBuf;
    }

    @JSONField(serialize = false)
    public TerBattery getTerBattery() {
        TerBattery bat = new TerBattery();
        bat.setMachineNO(this.mno);
        bat.setDt(new Date(this.time));
        bat.setBatteryEU((int) (Double.parseDouble(this.batvol) * 1000));
        bat.setSoc(0);
        bat.setBatteryRemaining(0);
        bat.setBatteryRelativelyRemaining((short) 0);
        return bat;
    }
}
